﻿using jutehui.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Configuration;
using GetData;
namespace jutehui.GetData
{
    public class jhsClass
    {
        /// <summary>
        /// 聚划算获取HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL()
        {
            List<Product> productList = new List<Product>();
            string jsonStr = GetJsonStr();
            GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string  errorMsg="";
            dt = CustomMethod.ListToDataTable<Product>(productList, "Product",ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product1 bll = new jutehui.BLL.Product1();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            { 
                return msg; 
            }
        }

        #region  聚划算网页上数据源中json数据解析

        private string GetJsonStr()
        {
            // 商品结束标记 window.insertPoints 开始标记  window.juListData = {"brandList"
            var htmlText = CustomMethod.GetWebHTML("https://ju.taobao.com/");
            Regex reg = new Regex(@"(<script>([\s\S]*)</script>)", RegexOptions.IgnoreCase); //截取script标签间的内容
            MatchCollection mc = reg.Matches(htmlText);
            string str = "";

            foreach (Match m in mc)
            {
                str += m.Value + "\r\n";
            }
            //所有商品json字符串
            string jsonStr = str.Substring(str.IndexOf("itemList\":") + 11, str.IndexOf(",\"md\"") - str.IndexOf("itemList\":") - 11);
            return jsonStr;
        }
        /// <summary>
        /// 将json数据反序列化为Dictionary
        /// </summary>
        /// <param name="jsonData">json数据</param>
        /// <returns></returns>
        private Dictionary<string, object> JsonToDictionary(string jsonData)
        {
            //实例化JavaScriptSerializer类的新实例
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                return jss.Deserialize<Dictionary<string, object>>(jsonData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 根据传入的一个商品信息json/串 解析出组装成需要的对象
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        private Product GetProductModel(string jsonStr)
        {
            try
            {
                Dictionary<string, object> dic = JsonToDictionary(jsonStr);//将Json数据转成dictionary格式
                //使用KeyValuePair遍历数据
                Product productInfo = new Product();
                productInfo.Source = "聚划算";

                foreach (KeyValuePair<string, object> item in dic)
                {
                    if (item.Value == "")
                    {
                        //如果键值为空则跳过
                        continue;
                    }
                    var infoItem = (Dictionary<string, object>)item.Value;

                    if (item.Key.ToString().ToLower() == "baseinfo")//获取baseInfo数据
                    {
                        productInfo.Plink = infoItem["itemUrl"].ToString();
                        productInfo.ImgUrl = infoItem["picUrl"].ToString();
                    }
                    else if (item.Key.ToString().ToLower() == "name")
                    {
                        productInfo.Pname = infoItem["shortName"].ToString();
                        productInfo.Description = infoItem["title"].ToString();
                    }
                    else if (item.Key.ToString().ToLower() == "price")
                    {
                        //if (infoItem["actPrice"] != DBNull.Value)
                        //{
                            productInfo.Price = infoItem["actPrice"].ToString();
                        ///}
                    }
                    else if (item.Key.ToString().ToLower() == "remind")
                    {
                        if (infoItem["soldCount"] != DBNull.Value)
                        {
                            productInfo.SoldCount = Convert.ToInt32(infoItem["soldCount"]);
                        }
                    }
                } 
                //商品类型 导航类型 默认值
                productInfo.ProductTypeId = 2;
                productInfo.TypeId = 2;
                productInfo.UpdateTime = DateTime.Now;
                productInfo.SoldCount = 0;
                productInfo.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
                return productInfo;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>  递归
        /// 传入所有上品牌json 根据起始索引和长度 截取每个商品json 解析成对象
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <param name="startIndex"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private void GetProductList(string jsonStr, List<Product> productList)
        {
            try
            {
                if (jsonStr.Contains("},{"))
                {
                    int endIndex = jsonStr.IndexOf("},{") + 1;//截取的长度
                    var jsonItem = jsonStr.Substring(0, endIndex);
                    var productItem = GetProductModel(jsonItem);

                    if (productItem != null)
                    {
                        productList.Add(productItem);
                    }

                    jsonStr = jsonStr.Remove(0, endIndex + 1);
                    GetProductList(jsonStr, productList);
                }
                //else
                //{ 
                //    break; 
                //}

                //return productList;
            }
            catch (Exception ex)
            {
                // return null;
            }
        }
        /// <summary>
        /// 根据传入的一个商品信息json/串 解析出组装成需要的对象  针对不同展示信息解析字段不同处理
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        private Product GetProductMainInfo(string jsonStr)
        {
            try
            {
                Dictionary<string, object> dic = JsonToDictionary(jsonStr);//将Json数据转成dictionary格式
                //使用KeyValuePair遍历数据
                Product productInfo = new Product();
                productInfo.Source = "聚划算";

                foreach (KeyValuePair<string, object> item in dic)
                {
                    if (item.Value == "")
                    {
                        //如果键值为空则跳过
                        continue;
                    }
                    var infoItem = (Dictionary<string, object>)item.Value;

                    if (item.Key.ToString().ToLower() == "baseinfo")//获取baseInfo数据
                    {
                        productInfo.Plink = infoItem["itemUrl"].ToString();
                        productInfo.ImgUrl = infoItem["picUrl"].ToString();
                    }
                    else if (item.Key.ToString().ToLower() == "name")
                    {
                        productInfo.Pname = infoItem["shortName"].ToString();
                        productInfo.Description = infoItem["title"].ToString();
                    }
                    else if (item.Key.ToString().ToLower() == "price")
                    {
                        if (infoItem["actPrice"] != DBNull.Value)
                        {
                            productInfo.Price = infoItem["actPrice"].ToString(); ;
                        }
                    }
                    else if (item.Key.ToString().ToLower() == "remind")
                    {
                        if (infoItem["soldCount"] != DBNull.Value)
                        {
                            productInfo.SoldCount = Convert.ToInt32(infoItem["soldCount"]);
                        }
                    }
                }
                return productInfo;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        #endregion

    }
}
